<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\common\Amap;
use app\common\UsersService;
use app\model\News;
use app\model\NewsClass;
use app\model\NewsComment;
use app\model\UsersRelated;
use app\model\UsersShield;
use app\Request;
use app\tool\Http;
use app\tool\ZhConvert;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\facade\Console;
use think\response\Json;

class NewsController extends BaseController
{
	protected array $middleware = ['Login' => [
		'except' => ['index', 'test', 'class_list', 'get_json', 'read', 'comment_list','caiji'],
	]];
	
	
	/**
	 * 屏蔽
	 * @param Request $request
	 * @return void
	 */
	function shield(Request $request)
	{
		$id = $request->post('id/d');
		UsersShield::create([
			'users_id'=>$request->users_id,
			'pro_id'=>$id,
			'type'=>'news'
		]);
		writeJson();
	}
	
	/**
	 * 新闻-列表
	 * @param int $class_id
	 * @param string $keyword
	 * @return Json
	 */
	public function index(Request $request,int $class_id, string $keyword)
	{
		
		$shield = UsersShield::where(['users_id'=>$request->users_id,'type'=>'news'])->column('pro_id');
		
		$rows = News::with(['issuer'])
			->whereTime('createtime', '-7 days')
			->when(!empty($class_id), function (Query $query) use ($class_id) {
				if ($class_id == 7) {
					$query->where('recommend', 1);
				} else {
					$query->where('class_id', $class_id);
				}
			})
			->whereNotIn('id',$shield)
			->when(!empty($keyword), function (Query $query) use ($keyword) {
				$query->whereLike('title_s|content_s', '%' . $keyword . '%');
			})
			->order(['id' => 'desc'])
			->paginate()
			->items();
		
		writeJson($rows);
	}
	
	/**
	 * 新闻-类目
	 * @return \think\response\Json
	 */
	function class_list()
	{
		
		$NewsClassModel = new NewsClass();
		$res = $NewsClassModel->order(['weigh' => 'desc'])->select();
		writeJson($res);
		
	}
	
	/**
	 * 保存新建的资源
	 *
	 * @param \think\Request $request
	 * @return \think\Response
	 */
	public function save(Request $request)
	{
		//
	}
	
	/**
	 * 新闻-详情
	 * @param $id
	 * @param Request $request
	 * @return Json
	 */
	public function read($id, Request $request)
	{
		$NewsModel = new News();
		$row = $NewsModel->with([
			'users',
			'issuer',
			'users_like' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id, 'type' => 'news']);
			},
			'users_collect' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id, 'type' => 'news']);
			}
		])->find($id);
		UsersService::footmark($id, $request->users_id, 'news');
		event('NewsIncBrowse', $id); //增加浏览数量
		
		writeJson($row);
	}
	
	/**
	 * 评论
	 * @param Request $request
	 * @return Json
	 */
	function comment(Request $request)
	{
		$params = $this->request->param();
		$ip = $request->ip();
		$params['ip'] = $ip;
		$ip = Amap::ip($ip);
		$ip = json_decode($ip);
		if ($ip->status == 1) {
			$params['city'] = $ip->province;
		} else {
			$params['city'] = '未知';
		}
		$res = NewsComment::create($params);
		foreach ($params['content'] as $v) {
			if ($v['type'] == 'at') {
				//@提醒  提醒接收人
				UsersRelated::create(['users_id' => $v['userId'], 'type' => 8, 'from_users_id' => $request->users_id, 'scene' => 'News', 'pro_id' => $res->id]);
			}
		}
		if (!empty($params['to_users_id'])) {
			//回复提醒  提醒接收人
			UsersRelated::create(['users_id' => $params['to_users_id'], 'type' => 1, 'from_users_id' => $request->users_id, 'scene' => 'News', 'pro_id' => $res->id]);
		} else {
			//评论提醒  提醒发布人
			$pro = News::find($params['news_id']);
			UsersRelated::create(['users_id' => $pro->users_id, 'type' => 2, 'from_users_id' => $request->users_id, 'scene' => 'News', 'pro_id' => $res->id]);
		}
		event('NewsIncComment', $params['news_id']); //增加评论数量
		$row = NewsComment::withCount(['comment'])->with([
			'users',
			'to_users',
			'users_like' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id, 'type' => 'news_comment']);
			}])->find($res->id);
		writeJson($row);
	}
	
	/**
	 * 评论列表
	 * @param int $news_id
	 * @param mixed $comment_id
	 * @param Request $request
	 * @return Json
	 */
	function comment_list(int $news_id, mixed $comment_id, Request $request)
	{
		$top_id = 0;
		if (!empty($comment_id)) {
			$row = NewsComment::find($comment_id);
			if ($row->pid == 0) {
				//顶级评论 放在第一条
				$top_id = $row->id;
			} else {
				//子评论 找出顶级评论
				$row = NewsComment::find($row->pid);
				$top_id = $row->id;
			}
		}
		
		$rows = NewsComment::where(['pid' => 0, 'news_id' => $news_id])
			->withCount('comment')
			->with([
				'users',
				'users_like' => function (Query $query) use ($request) {
					$query->where(['users_id' => $request->users_id, 'type' => 'news_comment']);
				},
				'comment' => function (Query $query) use ($request, $comment_id) {
					$query
						->with(['users', 'to_users', 'users_like' => function (Query $query) use ($request) {
							$query->where(['users_id' => $request->users_id, 'type' => 'news_comment']);
						}])
						->when(!empty($comment_id), function (Query $query) use ($comment_id) {
							$query->field("*,IF(id = $comment_id,1,0) AS top")->order(['top' => 'desc', 'id' => 'desc']);
						}, function (Query $query) {
							$query->order(['id' => 'desc']);
						})
						->limit($this->comment_list_rows);
				}])
			->when(!empty($comment_id), function (Query $query) use ($top_id) {
				$query->field("IF(id = $top_id,1,0) AS top")->order(['top' => 'desc', 'id' => 'desc']);
			}, function (Query $query) {
				$query->order(['id' => 'desc']);
			})
			->paginate()
			->items();
		writeJson($rows);
	}
	
	/**
	 * 评论详情
	 * @param int $id
	 * @param mixed $comment_id
	 * @param Request $request
	 * @return Json
	 */
	function comment_detail(int $id, mixed $comment_id, Request $request)
	{
		$child = false;
		if (!empty($comment_id)) {
			$row = NewsComment::find($comment_id);
			if ($row->pid != 0) {
				//二级评论
				$child = true;
			}
		}
		
		$rows = NewsComment::where(['pid' => $id])
			->with(['users', 'to_users', 'users_like' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id, 'type' => 'news_comment']);
			}])
			->when($child, function (Query $query) use ($comment_id) {
				$query->where('id', '<>', $comment_id);
			})
			->order(['id' => 'desc'])
			->paginate($this->comment_detail_rows)
			->items();
		writeJson($rows);
	}
	
	/**
	 * 评论点赞
	 * @param Request $request
	 * @return Json
	 */
	function comment_like(Request $request)
	{
		$id = $request->param('id');
		$res = UsersService::like($id, $request->users_id, 'news_comment');
		$res ? event('NewsCommentIncLike', $id) : event('NewsCommentDecLike', $id); //增加/减少  点赞数量
		if ($res) {
			$pro = NewsComment::find($id);
			UsersRelated::create(['users_id' => $pro->users_id, 'type' => 4, 'from_users_id' => $request->users_id, 'scene' => 'News', 'pro_id' => $id]);
		}
		writeJson($res);
	}
	
	/**
	 * 收藏
	 * @param Request $request
	 * @return Json
	 */
	function collect(Request $request)
	{
		$id = $request->post('id/d');
		$res = UsersService::collect($id, $request->users_id, 'news');
		$res ? event('NewsIncCollect', $id) : event('NewsDecCollect', $id); //增加/减少  收藏数量
		if ($res) {
			$pro = News::find($id);
			UsersRelated::create(['users_id' => $pro->users_id, 'type' => 7, 'from_users_id' => $request->users_id, 'scene' => 'News', 'pro_id' => $id]);
		}
		writeJson($res);
	}
	
	/**
	 * 点赞
	 * @param Request $request
	 * @return Json
	 */
	function like(Request $request)
	{
		$id = $request->post('id');
		$res = UsersService::like($id, $request->users_id, 'news');
		$res ? event('NewsIncLike', $id) : event('NewsDecLike', $id); //增加/减少  点赞数量
		if ($res) {
			$pro = News::find($id);
			UsersRelated::create(['users_id' => $pro->users_id, 'type' => 3, 'from_users_id' => $request->users_id, 'scene' => 'News', 'pro_id' => $id]);
		}
		writeJson($res);
	}
	
	function get_json()
	{
		
		ignore_user_abort(true); // 关闭浏览器 继续执行
		set_time_limit(0); // 执行时间为无限制
		ini_set("memory_limit","-1");
		$res = Http::get('https://www.talent.gov.hk/datagovhk/mip_sc.json');
		
		$res = json_decode($res);
		foreach ($res as $k) {
			$row = News::where(['unique' => $k->url])->find();
			if (!$row) {
				News::create([
					'users_id' => 3,
					'class_id' => 8,
					'issuer_id' => 24,
					'title_t' => $k->title ? ZhConvert::zh_auto($k->title) : '',
					'title_s' => $k->title ?? '',
					'content_t' => $k->content ? ZhConvert::zh_auto($k->content) : '',
					'content_s' => $k->content ?? '',
					'url' => $k->url,
					'unique' => $k->url
				]);
			}
		}
		
		$res = Http::get('https://api.data.gov.hk/v1/fso/majorspeech/search?lang=sc');
		$res = json_decode($res);
		$res = $res->results;
		foreach ($res as $k) {
			$row = News::where(['unique' => $k->link])->find();
			if (!$row) {
				News::create([
					'users_id' => 3,
					'class_id' => 8,
					'issuer_id' => 25,
					'title_t' => $k->title ? ZhConvert::zh_auto($k->title) : '',
					'title_s' => $k->title ?? '',
					'content_t' => $k->description ? ZhConvert::zh_auto($k->description) : '',
					'content_s' => $k->description ?? '',
					'url' => $k->link,
					'unique' => $k->link
				]);
			}
		}
		$res = Http::get('https://api.hkma.gov.hk/public/insight-articles?lang=sc');
		$res = json_decode($res);
		$res = $res->result->records;
		foreach ($res as $k) {
			$row = News::where(['unique' => $k->link])->find();
			if (!$row) {
				News::create([
					'users_id' => 3,
					'class_id' => 8,
					'issuer_id' => 26,
					'title_t' => $k->title ?? '',
					'title_s' => $k->title ? ZhConvert::zh_auto($k->title, 'zh-hant') : '',
					'url' => $k->link,
					'unique' => $k->link
				]);
			}
		}
		$res = Http::get('https://api.data.gov.hk/v1/sj/blog/search?lang=sc');
		$res = json_decode($res);
		$res = $res->results;
		foreach ($res as $k) {
			$row = News::where(['unique' => $k->link])->find();
			if (!$row) {
				News::create([
					'users_id' => 3,
					'class_id' => 8,
					'issuer_id' => 27,
					'title_t' => $k->title ? ZhConvert::zh_auto($k->title) : '',
					'title_s' => $k->title ?? '',
					'content_t' => $k->description ? ZhConvert::zh_auto($k->description) : '',
					'content_s' => $k->description ?? '',
					'url' => $k->link,
					'unique' => $k->link
				]);
			}
		}
		
		$res = Http::get('https://api.data.gov.hk/v1/pressrelease/search?official=SJ&type=press&lang=sc');
		$res = json_decode($res);
		$res = $res->results;
		foreach ($res as $k) {
			$row = News::where(['unique' => $k->link])->find();
			if (!$row) {
				News::create([
					'users_id' => 3,
					'class_id' => 8,
					'issuer_id' => 27,
					'title_t' => $k->title ? ZhConvert::zh_auto($k->title) : '',
					'title_s' => $k->title ?? '',
					'content_t' => $k->description ? ZhConvert::zh_auto($k->description) : '',
					'content_s' => $k->description ?? '',
					'url' => $k->link,
					'unique' => $k->link
				]);
			}
		}
		
		$res = Http::get('https://api.hkma.gov.hk/public/bank-svf-info/fraudulent-bank-scams?lang=tc');
		$res = json_decode($res);
		$res = $res->result->records;
		foreach ($res as $k) {
			if (!$k->pr_url && !$k->fraud_website_address) {
				continue;
			}
			$row = $k->pr_url ? News::where(['unique' => $k->pr_url])->find() : News::where(['unique' => $k->fraud_website_address])->find();
			if (!$row) {
				if ($k->fraud_website_address) {
					$eamil = '偽冒電郵：' . PHP_EOL;
					$web = '偽冒網站：' . PHP_EOL;
					$content = explode(';', $k->fraud_website_address);
					foreach ($content as $value) {
						$has = str_contains($value, '@');
						if ($has) {
							$eamil .= $value;
						} else {
							$web .= $value;
						}
					}
					$content = $eamil . PHP_EOL . $web . PHP_EOL;
				} else {
					$content = null;
				}
				
				News::create([
					'users_id' => 3,
					'class_id' => 10,
					'issuer_id' => 26,
					'title_t' => $k->alleged_name ?? '',
					'title_s' => $k->alleged_name ? ZhConvert::zh_auto($k->alleged_name, 'zh-hant') : '',
					'content_t' => $content ?? '',
					'content_s' => $content ? ZhConvert::zh_auto($content, 'zh-hant') : '',
					'unique' => $k->pr_url ?? $k->fraud_website_address
				]);
			}
		}
		
		$res = Http::get('https://api.data.gov.hk/v1/pressrelease/search?lang=sc&official=CE&type=press');
		$res = json_decode($res);
		$res = $res->results;
		foreach ($res as $k) {
			$row = News::where(['unique' => $k->link])->find();
			if (!$row) {
				News::create([
					'users_id' => 3,
					'class_id' => 8,
					'issuer_id' => 28,
					'title_t' => $k->title ? ZhConvert::zh_auto($k->title) : '',
					'title_s' => $k->title,
					'content_t' => $k->description ? ZhConvert::zh_auto($k->description) : '',
					'content_s' => $k->description ?? '',
					'url' => $k->link,
					'unique' => $k->link
				]);
			}
		}
		
		writeJson();
	}
	
	function caiji($type)
	{
		$output = Console::call('zncaiji',[$type]);
		return $output->fetch();
	}
	
}
